<script setup>
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { requirementListService, requirementAddService, requirementUpdateService, requirementDeleteService } from '@/api/iimApi/requirement.js';
import { useProjectStore } from '@/stores/projectStore';

const projectStore = useProjectStore();
// 需求列表数据模型
const requirements = ref([]);
const filteredRequirements = ref([]);
const requirementName = ref('');

// 分页条数据模型
const pageNum = ref(1); // 当前页
const total = ref(0); // 总条数
const pageSize = ref(3); // 每页条数

// 控制抽屉是否显示
const visibleDrawer = ref(false);
const isEdit = ref(false); // 控制是否为编辑状态

// 添加表单数据模型
const requirementModel = ref({
  id: null,
  name: '',
  identifier: '',
  parentId: '',
  requirementDescription: '',
  performanceDescription: ''
});

const rules = {
  name: [{ required: true, message: '请输入需求名称', trigger: 'blur' }],
  identifier: [{ required: true, message: '请输入需求标识', trigger: 'blur' }],
  requirementDescription: [{ required: false, message: '请输入需求描述', trigger: 'blur' }],
  performanceDescription: [{ required: false, message: '请输入性能描述', trigger: 'blur' }]
};

// 打开添加需求表单
const openAddRequirement = () => {
  isEdit.value = false;
  requirementModel.value = {
    id: null,
    name: '',
    identifier: '',
    parentId: '',
    requirementDescription: '',
    performanceDescription: ''
  };
  visibleDrawer.value = true;
};

// 获取需求列表数据
const requirementList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    name: requirementName.value ? requirementName.value : null
  };
  let result = await requirementListService(projectStore.selectedProject.id, params);

  // 渲染视图
  requirements.value = result.data.map(item => ({
    id: item.id,
    name: item.name,
    identifier: item.identifier,
    parentId: item.parentId,
    requirementDescription: item.requirementDescription,
    performanceDescription: item.performanceDescription
  }));
  filteredRequirements.value = requirements.value;
  total.value = filteredRequirements.value.length;
};

// 计算当前页显示的数据
const paginatedRequirements = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredRequirements.value.slice(start, end);
});

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  requirementList();
};

// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  requirementList();
};

// 过滤需求列表
const filterRequirements = () => {
  const query = requirementName.value.toLowerCase();
  filteredRequirements.value = requirements.value.filter(requirement => 
    requirement.name.toLowerCase().includes(query) || 
    requirement.identifier.toLowerCase().includes(query)
  );
  total.value = filteredRequirements.value.length;
};

// 重置搜索
const resetSearch = () => {
  requirementName.value = '';
  filterRequirements();
};

// 添加需求
const addRequirement = async () => {
  let result;
  if (isEdit.value) {
    result = await requirementUpdateService(requirementModel.value, projectStore.selectedProject.id);
    ElMessage.success(result.msg ? result.msg : '修改成功');
  } else {
    result = await requirementAddService(requirementModel.value, projectStore.selectedProject.id);
    ElMessage.success(result.msg ? result.msg : '添加成功');
  }
  visibleDrawer.value = false;
  requirementList();
};

// 编辑需求
const editRequirement = (requirement) => {
  isEdit.value = true;
  requirementModel.value = { ...requirement };
  visibleDrawer.value = true;
};

// 删除需求
const deleteRequirement = async (requirement) => {
  try {
    await ElMessageBox.confirm(
      `此操作将永久删除需求 "${requirement.name}" 及其所有下级需求和关联元素信息, 是否继续?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    await requirementDeleteService(requirement.id, projectStore.selectedProject.id);
    ElMessage.success('删除成功');
    requirementList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 初始化需求列表
requirementList();

// 计算属性：根据 parentId 查找并显示相应的 identifier
const requirementsWithParentIdentifier = computed(() => {
  return filteredRequirements.value.map(requirement => {
    const parentRequirement = requirements.value.find(r => r.id === requirement.parentId);
    return {
      ...requirement,
      parentIdentifier: parentRequirement ? parentRequirement.identifier : ''
    };
  });
});

// 过滤掉当前需求本身的需求列表
const filteredRequirementsForSelect = computed(() => {
  return requirements.value.filter(requirement => requirement.id !== requirementModel.value.id);
});
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>需求定义管理</span>
        <div class="extra">
          <el-button type="primary" @click="openAddRequirement">添加需求</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="需求名称或标识：">
        <el-input placeholder="请输入需求名称或标识" v-model="requirementName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="filterRequirements">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 需求信息列表 -->
    <el-table :data="requirementsWithParentIdentifier" style="width: 100%">
      <el-table-column prop="name" label="需求名称" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="identifier" label="需求标识" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="parentIdentifier" label="上级需求标识" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="requirementDescription" label="需求描述" show-overflow-tooltip></el-table-column>
      <el-table-column prop="performanceDescription" label="性能描述" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button @click="editRequirement(scope.row)" type="primary" size="small">修改</el-button>
          <el-button @click="deleteRequirement(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" :title="isEdit ? '修改需求' : '添加需求'" direction="rtl" size="50%">
      <!-- 添加需求表单 -->
      <el-form :model="requirementModel" :rules="rules" label-width="100px">
        <el-form-item label="需求名称" prop="name">
          <el-input v-model="requirementModel.name" placeholder="请输入需求名称"></el-input>
        </el-form-item>
        <el-form-item label="需求标识" prop="identifier">
          <el-input v-model="requirementModel.identifier" placeholder="请输入需求标识"></el-input>
        </el-form-item>
        <el-form-item label="上级需求标识">
          <el-select v-model="requirementModel.parentId" placeholder="请选择上级需求标识">
            <el-option
              :key="null"
              :label="'无'"
              :value="null"
            />
            <el-option
              v-for="requirement in filteredRequirementsForSelect"
              :key="requirement.id"
              :label="requirement.identifier"
              :value="requirement.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="需求描述" prop="requirementDescription">
          <el-input type="textarea" v-model="requirementModel.requirementDescription" placeholder="请输入需求描述"></el-input>
        </el-form-item>
        <el-form-item label="性能描述" prop="performanceDescription">
          <el-input type="textarea" v-model="requirementModel.performanceDescription" placeholder="请输入性能描述"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addRequirement">{{ isEdit ? '修改' : '添加' }}</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>